import logging
import pickle

from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow

from buzz import BuzzClient
from microsyndutils import UserAccount
from microsyndutils import Session

class AuthorizationHandler(webapp.RequestHandler):
    @login_required
    def get(self):
        user = users.get_current_user()
        session_key = 'session' + user.user_id()
        session = pickle.loads(memcache.get(session_key))
        targets = session.targets
        if targets['buzz'] == 'yes':
            credentials = StorageByKeyName(
                UserAccount, user.user_id(), 'buzz_credentials').get()
            if credentials is None or credentials.invalid == True:
                self.authorize_buzz()
                return  # so redirect works
            else:
                BuzzClient.post(session.message)
                targets['buzz'] = ''
                # TODO BUG: updated targets are not saved in session,
                # if facebook is enabled, buzz message will be posted again
                # when facebook auth page returns control to this handler
        if targets['facebook'] == 'yes':
            self.authorize_facebook()
            targets['facebook'] = ''
        if targets['weibo'] == 'yes':
            self.authorize_weibo()
            targets['weibo'] = ''
        if targets['twitter'] == 'yes':
            self.authorize_twitter()
            targets['twitter'] = ''
        memcache.delete(session_key)
        self.redirect('/')

    def authorize_buzz(self):
        user = users.get_current_user()
        flow = OAuth2WebServerFlow(
            # Visit https://code.google.com/apis/console to
            # generate your client_id, client_secret and to
            # register your redirect_uri.
            client_id='127313744327.apps.googleusercontent.com',
            client_secret='_iDprzp78LMYC43H0f5EZRNA',
            scope='https://www.googleapis.com/auth/buzz',
            user_agent='buzz-cmdline-sample/1.0',
            domain='anonymous',
            xoauth_displayname='Google App Engine Example App')
        callback = self.request.relative_url('/buzz_auth_return')
        authorize_url = flow.step1_get_authorize_url(callback)
        logging.info(authorize_url)
        memcache.set('buzz' + user.user_id(), pickle.dumps(flow))
        self.redirect(authorize_url)

    def authorize_facebook():
        pass

    def authorize_weibo():
        pass

    def authorize_twitter():
        pass



